package com.cjm.algorithm.leetcode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

public class LevelOrder0429 {
    public List<List<Integer>> levelOrder1(Node root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> level = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                Node node = queue.poll();
                level.add(node.val);
                for (Node child : node.children) {
                    if (child != null) {
                        queue.add(child);
                    }
                }
            }
            res.add(level);
        }
        return res;
    }

    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        Queue<Node> queue = new ArrayBlockingQueue<Node>(100000);
        queue.add(root);
        int cur = 1;
        int nextLen = 0;
        while (!queue.isEmpty()) {
            List<Integer> curList = new ArrayList<>();
            for (int i = 0; i < cur; i++) {
                Node curNode = queue.poll();
                curList.add(curNode.val);
                List<Node> children = curNode.children;
                for (Node child : children) {
                    if (child != null) {
                        queue.add(child);
                        nextLen++;
                    }
                }
            }
            cur = nextLen;
            nextLen = 0;
            res.add(curList);
        }
        return res;
    }

    static class Node {
        public int val;
        public List<Node> children;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, List<Node> _children) {
            val = _val;
            children = _children;
        }
    }

    ;
}
